"""SQLAlchemy models for activation system."""
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, func, Index
from sqlalchemy.orm import relationship
from .database import Base

class ActivationCode(Base):
    id = Column(Integer, primary_key=True)
    raw_code = Column(String(32), unique=True, nullable=False)
    code_hash = Column(String(64), unique=True, nullable=False, index=True)
    duration_days = Column(Integer, nullable=True)  # None means perpetual
    quota = Column(Integer, default=1)
    enabled = Column(Boolean, default=True)
    comment = Column(String(120))
    licenses = relationship("License", back_populates="activation_code", cascade="all, delete-orphan")

class License(Base):
    id = Column(Integer, primary_key=True)
    code_id = Column(Integer, ForeignKey("activationcode.id", ondelete="CASCADE"), nullable=False)
    device_hash = Column(String(64), nullable=False, index=True)
    issued_at = Column(DateTime, server_default=func.now())
    expires_at = Column(DateTime, nullable=True)
    activation_code = relationship("ActivationCode", back_populates="licenses")
    __table_args__ = (Index("ix_code_device_unique", "code_id", "device_hash", unique=True),)
